// pages/pay/Pay.js
let Zan = require('../../dist/index.js');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();

Page(Object.assign({}, Zan.TopTips, Zan.Switch, {

  /**
   * 页面的初始数据
   */
  data: {
    orderType: 0, // 0=送货上门，1=到店自己提
    Distributions: -1, // 后台设置的配送方式显示 0=送货上门，1=到店自提,2=两种都有
    userName: null,
    deliverAddress: null,
    userPhone: null,
    products: [],
    totalPrice: 0,
    showDialog: false,
    days: [],
    times: [],
    day: null,
    time: null,
    date: null,
    packing: 0, // 包装费
    freight: 0,
    store: null,
    couponPrice: 0, // 可优惠金额
    couponAmount: 0, // 优惠券面值
    couponId: 0, // 优惠券Id
    items: ['代金券', '会员折扣'],
    couponType: 0, // 优惠方式 
    member: null,
    liuyan: '',
    shoppingCartId: null,
    selectCouponed: true,
    coupon: null,
    content: "",
    allPrice: 0, // 总价
    integralPrice: 0, // 积分可低多少钱
    discountPrice: 0, // 实付金额
    zhekou: 0,
    orderId: null,
    orderNO: null,
    orderDesc: null,
    canPay: true,
    againPay: 0,
    isMax: false,
    distributorId: "",
    useCoupon: false, // 是否使用优惠券
    useIntegral: false, // 是否使用积分
    integralRule: null,
    integral: 0,
    animationData: {},
    couponSwitch: {
      checked: false
    },
    integralSwitch: {
      checked: false
    },
    jifendikou: 0,
    mode1: 0,
    mode2: 1,
    radiochecked: 0,
    shop_details: {},
    dateStr: '自提时间',
    formId: '',
    count: 0,
    multiIndex: [0, 0],
    StartingPrice:0,
    StartStatus:true,
    weight:0,
    isService:true,
    header:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    let days = getDays();
    this.setData({ days: days, times: getTimes2(), day: days[0] });

    // 获取可用代金券
    WxNotificationCenter.addNotification("GetCanUseCoupon", this.getCanUseCoupon, this)
    // 获取回调门店信息
    // WxNotificationCenter.addNotification("GetStoreInfo", this.getStoreInfo, this)

    if (options.shoppingCar) {
      let products = JSON.parse(decodeURIComponent(options.shoppingCar));
      console.log("=============shoppingCar===============");
      console.log(products);
      let store = JSON.parse(decodeURIComponent(options.store));
      getCount(this, products);
      this.setData({
        products: products,
        store: store
      })
    }

    
    network._post_json(this, api.getTenantDistribution, { storeId: this.data.store.id }, successDistribution);
    console.log(app.globalData.userInfo);
    //判断会员卡到期
    if (app.globalData.userInfo.typeId) {
      if (app.globalData.userInfo.memberendtime) {
        console.log(app.globalData.userInfo);
        var NowTime = new Date().getTime();
        var total_micro = app.globalData.userInfo.memberendtime * 1000 - NowTime;
        console.log("endTime" + app.globalData.userInfo.memberendtime * 1000);
        console.log("NowTime" + NowTime);
        console.log("total_micro" + total_micro);
        if (total_micro <= 0) {
          this.setData({
            items: ['代金券'],
          })
        } else {
          network._post_json(this, api.getUserMemberType, { typeId: app.globalData.userInfo.typeId }, memberTypeSuccess);
        }
      } else {
        network._post_json(this, api.getUserMemberType, { typeId: app.globalData.userInfo.typeId }, memberTypeSuccess);
      }
    }else{
      this.setData({
        items: ['代金券'],
      })
    }
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        let latitude = res.latitude;
        let longitude = res.longitude;
        that.setData({
          lng: longitude,
          lat: latitude
        })
      }
    })

    //生成预订单号
    network._post_json(this,api.getOrderId, {}, getOrderIdSuccess);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("GetCanUseCoupon", this);
    // WxNotificationCenter.removeNotification("GetStoreInfo", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  getInfo: function (e) {
    console.log(e.detail.userInfo);
    if (e.detail.userInfo) {
      app.globalData.userInfo.avatarUrl = e.detail.userInfo.avatarUrl;
      app.globalData.userInfo.nickName = e.detail.userInfo.nickName;
      app.globalData.userInfo.gender = e.detail.userInfo.gender;
      this.setData({
        userInfo: app.globalData.userInfo,
        avatarUrl: e.detail.userInfo.avatarUrl,
        nickName: e.detail.userInfo.nickName,
      });
      console.log('+++++++++++++++++++++++++++++++')
      console.log(e.detail.userInfo.gender);
      network._post_json(this, api.modifyUserInfo, { nickName: this.data.nickName, avatarUrl: this.data.avatarUrl, gender: e.detail.userInfo.gender }, usersuccess);
    }
  },

  bindMultiPickerChange: function (e) {
    this.setData({
      multiIndex: e.detail.value,
      date: new Date().getTime() + e.detail.value[0] * 24 * 60 * 60 * 1000,
      dateLink: e.detail.value[1],
      dateStr: this.data.day[0][e.detail.value[0]] + this.data.day[1][e.detail.value[1]]
    })
  },

  bindTextArea: function (e) {
    this.setData({
      content: e.detail.value
    })
  },

  /**
   * 送货上门
   */
  express: function (e) {
    if (this.data.distribution.logistics) {
      let packingCharge = parseInt(this.data.distribution.logistics.packingCharge);
      this.setData({
        packingCharge: packingCharge,
      })

      let total = getTotal(this, this.data.products, packingCharge, this.data.freight);
      this.setData({
        totalPrice: total,
      })

      if (this.data.distribution.logistics.deliverMethod == 1){
        let StartingPrice = this.data.distribution.logistics.orderStartingPrice;
        console.log(StartingPrice);
        this.setData({
          StartingPrice: StartingPrice
        })
      }
      
      this.setData({
        orderType: 0,
      })
    } else {
      this.showZanTopTips(this.prompt, '本店不支持配送上门');
    }
    console.log("orderType---------------------" + this.data.orderType);
    console.log("Distributions---------------------" + this.data.Distributions);
  },
  express2:function(){
    this.showZanTopTips(this.prompt, '购物车有服务商品需要上门自提');
  },

  /**
   * 自提
   */
  myselfTalk: function (e) {
    if (this.data.distribution.pickedUp) {
      let packingCharge = parseInt(this.data.distribution.pickedUp.packingCharge);
      this.setData({
        packingCharge: packingCharge,
      })

      let total = getTotal(this, this.data.products, packingCharge, 0);
      this.setData({
        totalPrice: total,
      })
      
      this.setData({
        orderType: 1
      })
    } else {
      this.showZanTopTips(this.prompt, '本店不支持到店自提');
    }
    console.log("orderType---------------------" + this.data.orderType);
    console.log("Distributions---------------------" + this.data.Distributions);
  },
  /**
   * 选择地址
   */
  getAddress: function (e) {
    var that = this;
      wx.chooseAddress({
        success: function (res) {
          that.setData({
            userName: res.userName,
            deliverAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo,
            userPhone: res.telNumber
          })
          if (that.data.distribution.logistics.deliverMethod == 2) {
            var totalFee = parseInt(that.data.totalPrice) - parseInt(that.data.couponPrice);
            network._post_json(that, api.queryDeliverFee, { orderId: that.data.OrderId, storeId: that.data.store.id, address: that.data.deliverAddress, userName: that.data.userName, userPhone: that.data.userPhone, total: totalFee }, Feesuccess);
          }
        }
      })
  },

  /**
   * 弹出框开关
   */
  toggleDialog() {
    this.setData({
      showDialog: !this.data.showDialog
    })
  },

  /**
   * 选择日期
   */
  chooseDay: function (e) {
    let index = e.currentTarget.dataset.index;
    for (let i = 0; i < this.data.days.length; i++) {
      if (i == index) {
        this.data.days[i].active = true;
        if (i == 0){
          this.setData({
            times: getTimes2()
          })
        }else{
          this.setData({
            times: getTimes()
          })
        }
      } else {
        this.data.days[i].active = false;
      }

    }
    this.setData({
      days: this.data.days,
      day: this.data.days[index]
    })
  },

  /**
   * 选择时间
   */
  chooseTime: function (e) {
    let time = e.currentTarget.dataset.time;
    this.setData({
      time: time,
      date: this.data.day.date + '(' + this.data.day.week + ') ' + time.name,
      showDialog: !this.data.showDialog
    })
  },

  /**
   * 选择优惠方式
   * 0代金券 1会员折扣
   */
  radioButtonTap: function (e) {
    // console.log(e);
    this.setData({
      couponType: e.detail,
    })

    if (e.detail == 1) {

      if (this.data.member && this.data.member.rule.isMemBerShop == 1) {
        // 折扣
        if (this.data.orderType == 1) {
          var totalproPrice = this.data.totalPrice - this.data.packingCharge;
        }else{
          var totalproPrice = this.data.totalPrice - this.data.packingCharge - this.data.freight;
        }
        
        console.log(totalproPrice);
        this.setData({
          couponPrice: totalproPrice - parseInt(totalproPrice * this.data.member.rule.memberDiscounts / 10)
        })
      } else {
        // 会员价
        // let packingCharge = parseInt(this.data.distribution.logistics.packingCharge);
        if (this.data.orderType == 1){
          let total = getMemberTotal(this, this.data.products, this.data.packingCharge, 0);
          console.log();
          this.setData({
            couponPrice: this.data.totalPrice - total
          })
        }else{
          let total = getMemberTotal(this, this.data.products, this.data.packingCharge, this.data.freight);
          this.setData({
            couponPrice: this.data.totalPrice - total
          })
        }
        
        
      }
    } else {
      if (this.data.orderType == 1) {
        let total = getTotal(this, this.data.products, this.data.packingCharge, 0);
        this.setData({
          totalPrice: total,
        })
      } else {
        let total = getTotal(this, this.data.products, this.data.packingCharge, this.data.freight);
        this.setData({
          totalPrice: total,
        })
      }
      this.setData({
        couponPrice: this.data.couponAmount
      })
    }
  },

  /**
   * 选择优惠券
   */
  chooseCoupon: function (e) {
    var productId = [];
    for (var i = 0; i < this.data.products.length; i++) {
      productId.push(this.data.products[i].id)
    }
    wx.navigateTo({
      url: '/pages/myself/coupon/ChooseCoupon?price=' + (this.data.totalPrice - this.data.packing - this.data.freight),
    })
  },

  /**
   * 获取选择的优惠券
   */
  getCanUseCoupon: function (coupon) {
    console.log(coupon)
    this.setData({
      couponAmount: coupon.value2,
      couponPrice: coupon.value2,
      couponId: coupon.id
    })
  },

  formIdSubmit: function (e) {
    this.setData({
      formId: e.detail.formId
    })
  },

  
  radioChange: function (e) {
    var radiotxt = e.detail.value;
    if (radiotxt == "送货上门") {
      this.setData({
        mode1: 0,
        mode2: 1,
        radiochecked: 0
      })
    } else {
      this.setData({
        mode1: 1,
        mode2: 0,
        radiochecked: 1
      })
    }
  }
}))
var usersuccess = function(that,res){
  /**
  * 选择支付方式
  */
  let data = {};
  let products = [];
  console.log("============购物车商品==============");
  console.log(that.data.products);
  for (let i = 0; i < that.data.products.length; i++) {
    let product = {};
    product.productId = that.data.products[i].id;
    product.count = that.data.products[i].count;
    if (that.data.products[i].specId) {
      product.specid = that.data.products[i].specId;
    }
    products.push(product);
  }
  data.products = products;
  if (that.data.couponType == 0) {
    data.couponId = that.data.couponId;
  } else {
    if (that.data.member) {
      data.memberId = that.data.member.membertype_id;
    }
  }
  data.orderId = that.data.OrderId;
  data.packingfee = that.data.packing;

  data.storeId = that.data.store.id;
  data.content = that.data.content;
  // data.orderType = that.data.orderType;
  if ((that.data.distribution.logistics && that.data.orderType == 0) || that.data.orderType == 2) { // 线上
    data.orderType = 0;
    data.freight = that.data.freight;
    if (that.data.deliverAddress) {
      data.deliverAddress = that.data.deliverAddress;
      data.userName = that.data.userName;
      data.userPhone = that.data.userPhone;
      if (that.data.time) {
        //data.subscribeDate = that.data.day.time + that.data.time.value;
        data.subscribeDate = that.data.day.dateDetails + ' ' + that.data.time.name;
      }
      if (that.data.StartingPrice) {

      }
      network._post_json(that, api.order, data, success);
    } else {
      that.showZanTopTips(that.prompt, '请设置收货地址');
    }
  } else if (that.data.distribution.pickedUp && that.data.orderType == 1) { // 线下
    data.orderType = 1;
    if (that.data.time) {
      //data.subscribeDate = that.data.day.time + that.data.time.value;
      data.subscribeDate = that.data.day.dateDetails + ' ' + that.data.time.name;
      network._post_json(that, api.order, data, success);
    } else {
      that.showZanTopTips(that.prompt, '请选择自提时间');
    }
  }
}


/**
 * 获得日期
 */
var getDays = function () {
  let week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  let date = utils.formatDate07(new Date());
  let time = new Date(date.replace(/-/g, '/')).getTime();
  let days = [];
  for (let i = 0; i < 4; i++) {
    let day = {};
    day.time = time + (24 * 60 * 60 * 1000) * i;
    day.active = false;
    if (i == 0) {
      day.active = true;
      day.date = '今天';
      
    } else if (i == 1) {
      day.date = '明天';
    } else {
      var month = new Date(day.time).getMonth() + 1;
      var day01 = new Date(day.time).getDate();
      day.date = month + '月' + day01 + '日';
    }
    day.dateDetails = utils.formatDate02(new Date(day.time));
    day.week = week[new Date(day.time).getDay()];
    days.push(day);
  }
  console.log(days);
  return days;
}

/**
 * 获取时间
 */
var getTimes = function () {
  let times = [];
  for (let i = 10; i <= 22; i++) {
    let time = {};
    time.name = i + ':00';
    time.value = i * 60 * 60 * 1000;
    times.push(time)
  }
  return times;
}
var getTimes2 = function () {
  let times = [];
  var date = new Date();
  var h = date.getHours();
  for (let i = h; i <= 22; i++) {
    let time = {};
    time.name = i + ':00';
    time.value = i * 60 * 60 * 1000;
    times.push(time)
  }
  return times;
}
// 清空购物车
// 生成订单
var success = function (that, res) {
  if (res.data.data){
    let allProId = [];
    for (var c = 0; c < that.data.products.length; c++) {
      let ProIdItems = that.data.products[c].carid;
      allProId.push(ProIdItems);
    }
    allProId = allProId.join(',');
    if (that.data.products){
      network._post_json(that, api.delShoppingCart, { shoppingCarId: allProId, is_del: 1 }, delSuccess);
    }
    
  }
  let order = {};
  
  order.orderId = res.data.data.orderId;
  order.orderNO = res.data.data.orderNo;
  order.totalPrice = that.data.totalPrice;
  order.couponPrice = that.data.couponPrice;
  wx.redirectTo({
    url: '/pages/pay/ChoosePay?order=' + JSON.stringify(order) + '&store=' + encodeURIComponent(JSON.stringify(that.data.store))
  })
  // if (res.data.data) {
  //   that.setData({
  //     orderId: res.data.data.id,
  //     orderNO: res.data.data.orderNO,
  //     OrderDesc: res.data.data.orderDesc,
  //   })
  //   // if (that.data.selected) { // 微信支付
  //   /**
  //   * 获取个人及商家信息
  //   */
  //   if (app.globalData.userAndTenantInfo) {
  //     // 购买
  //     network._post_json(that, api.wxPay, {
  //       shoppingCartIds: that.data.shoppingCartIds,
  //       products: that.data.products,
  //       appId: app.globalData.appId,
  //       orderId: res.data.data.orderNO,
  //       OrderDesc: res.data.data.orderDesc,
  //       totalFee: res.data.data.total
  //     }, wxPaySuccess);
  //   } else {
  //     app.userAndTenantInfoCallback = res => {
  //       // 购买
  //       network._post_json(that, api.wxPay, {
  //         shoppingCartIds: that.data.shoppingCartIds,
  //         products: that.data.products,
  //         appId: app.globalData.appId,
  //         orderId: res.data.data.orderNO,
  //         OrderDesc: res.data.data.orderDesc,
  //         totalFee: res.data.data.total
  //       }, wxPaySuccess);
  //     }
  //   }
  // }
}
var delSuccess = function (that, res) {
  if (res.data.data) {
    
  }
}
// 修改订单
var modifySuccess = function (that, res) {
  if (res.data.message == '修改订单成功') {
    if (app.globalData.userAndTenantInfo) {
      // 购买
      network._post_json(that, api.wxPay, {
        shoppingCartIds: that.data.shoppingCartIds,
        products: that.data.products,
        appId: app.globalData.appId,
        orderId: res.data.data.orderNO,
        OrderDesc: res.data.data.orderDesc,
        totalFee: res.data.data.total
      }, wxPaySuccess);
    } else {
      app.userInfoCallback = res => {
        // 购买
        network._post_json(that, api.wxPay, {
          shoppingCartIds: that.data.shoppingCartIds,
          products: that.data.products,
          appId: app.globalData.appId,
          orderId: res.data.orderNO,
          OrderDesc: res.data.orderDesc,
          totalFee: res.data.total
        }, wxPaySuccess);
      }
    }
  }
}

// 微信支付结果
var wxPaySuccess = function (that, res) {
  if (res.data.data) {
    wx.requestPayment({
      timeStamp: res.data.data.timeStamp,
      nonceStr: res.data.data.nonceStr,
      package: res.data.data.package,
      signType: res.data.data.signType,
      paySign: res.data.data.paySign,
      success: function (res) {
        if (that.data.orderNO) {
          wx.redirectTo({
            url: "/pages/myself/order/OrderDetails?orderId=" + that.data.orderId
          })
        } else {
          wx.navigateTo({
            url: "/pages/myself/order/OrderDetails?orderId=" + that.data.orderId
          })
        }
        //获取页面栈
        // var pages = getCurrentPages();
        // if (pages.length > 1) {
        //   //上一个页面实例对象
        //   var prePage = pages[pages.length - 2];
        //   if (prePage.refresh && typeof (prePage.refresh) == "function") {
        //     prePage.refresh();
        //   }
        // }
        // wx.navigateBack({

        // })
        if (that.data.formId) {
          network._post_json(that, api.sendCoupn, { formId: that.data.formId, type: 3, price: that.data.discountPrice }, sendCoupnSuccess);
        }
      },
      fail: function (res) {
        // wx.navigateTo({
        //   url: "/pages/myself/order/OrderDetails?orderId=" + that.data.orderId
        // })
      },
    });
  }
}

/**
 * 商品总价
 */
var getTotal = function (that, items, packingCharge, freight) {
  let price = 0;
  let pk = packingCharge;
  for (let i = 0; i < items.length; i++) {
    price += parseInt(items[i].price) * items[i].count;
    // pk += packingCharge * items[i].count;
  }

  that.setData({
    packing: pk
  })
  return price + pk + parseInt(freight);
}

/**
 * 会员总价
 */
var getMemberTotal = function (that, items, packingCharge, freight) {
  let price = 0;
  let pk = packingCharge;
  for (let i = 0; i < items.length; i++) {
    price += items[i].memberPrice * items[i].count;
    // pk += packingCharge * items[i].count;
  }

  that.setData({
    packing: pk
  })
  return price + pk + parseInt(freight);
}

var successDistribution = function (that, res) {
  that.setData({
    distribution: res.data.data
  })

  let logistics = res.data.data.logistics;
  // 配送费
  if (logistics) {
    if (logistics.packingCharge) {
      var packingCharge = parseInt(logistics.packingCharge);
    } else {
      var packingCharge = 0;
    }
    if (logistics.deliverMethod == 0) {
      //物流配送
      let LogisRrule = logistics.LogisticalRrule;
      if (logistics.freight_type == 0) {
        let freight = LogisRrule.unifiedmoney;
        that.setData({
          freight: freight
        })
      } else if (logistics.freight_type == 1) {
        if (that.data.count > parseInt(LogisRrule.first_num)){
          let freight = LogisRrule.first_money + (that.data.count - LogisRrule.first_num) / LogisRrule.continued_num * LogisRrule.continued_money;
          that.setData({
            freight: freight
          })
        }else{
          let freight = LogisRrule.first_money;
          that.setData({
            freight: freight
          })
        }
        
      } else if (logistics.freight_type == 2) {
        if (that.data.weight > parseInt(LogisRrule.first_num)){
          let freight = LogisRrule.first_money + (that.data.weight - LogisRrule.first_num) / LogisRrule.continued_num * LogisRrule.continued_money;
          that.setData({
            freight: freight
          })
        }else{
          let freight = LogisRrule.first_money;
          that.setData({
            freight: freight
          })
        }
        
      }
    } else if (logistics.deliverMethod == 1) {
      //商家直送
      let distanceIncrease = JSON.parse(logistics.distanceIncrease);
      let nocturnalPriceIncrease = JSON.parse(logistics.nocturnalPriceIncrease);
      let weightIncrease = JSON.parse(logistics.weightIncrease);
      let freight = parseInt(logistics.freight);
      //重量加价
      console.log("重量"+that.data.weight);
      if (that.data.weight <= 1){
        freight = freight + parseInt(weightIncrease.weightIncrease_1_val)
      } else if (that.data.weight > 1 && that.data.weight <=5){
        freight = freight + parseInt(weightIncrease.weightIncrease_1_val) + (that.data.weight - 1) * parseInt(weightIncrease.weightIncrease_1_5_val)
      } else if (that.data.weight > 5 && that.data.weight <= 10) {
        freight = freight + parseInt(weightIncrease.weightIncrease_1_val) + 4 * parseInt(weightIncrease.weightIncrease_1_5_val) + (that.data.weight - 5) / 5 * parseInt(weightIncrease.weightIncrease_5_10_val)
      } else if (that.data.weight > 10) {
        freight = freight + parseInt(weightIncrease.weightIncrease_1_val) + 4 * parseInt(weightIncrease.weightIncrease_1_5_val) + (that.data.weight - 5) / 5 * parseInt(weightIncrease.weightIncrease_5_10_val)
      }
      //距离加价
      let distance = Math.floor(app.globalData.store.distance / 1000);
      console.log("距离" + distance);
      if (distance > 1 && distance <= 3) {
        freight = freight + parseInt(distanceIncrease.distanceIncrease_1_3_val)
      } else if (distance > 3 && distance <= 5) {
        freight = freight + parseInt(distanceIncrease.distanceIncrease_1_3_val) + parseInt(distanceIncrease.distanceIncrease_3_5_val)
      } else if (distance > 5) {
        freight = freight + parseInt(distanceIncrease.distanceIncrease_1_3_val) + parseInt(distanceIncrease.distanceIncrease_3_5_val)
      }
      //夜间加价
      var NowTime = new Date().getHours();
      console.log("NowTime" + NowTime);
      if (NowTime >= 22 || NowTime < 8){
        freight = freight + weightIncrease.weightIncrease_1_val + nocturnalPriceIncrease.nocturnalPriceIncrease_22_08_val
      }
      that.setData({
        freight: freight
      })
    } else if (logistics.deliverMethod == 2) {
      //同城快递


    }

    let total = getTotal(that, that.data.products, packingCharge, that.data.freight);
    that.setData({
      totalPrice: total,
      orderType: 0,
      Distributions:0,
      packingCharge: packingCharge
    })
  }

  if (res.data.data.pickedUp) {
    let packingCharge = parseInt(res.data.data.pickedUp.packingCharge);
    let total = getTotal(that, that.data.products, packingCharge, 0);
    console.log(total);
    that.setData({
      totalPrice: total,
      orderType: 1,
      Distributions:1,
      packingCharge: packingCharge
    })
  }
  if (logistics && res.data.data.pickedUp) {
    if (logistics.packingCharge){
      var packingCharge = parseInt(logistics.packingCharge);
    }else{
      var packingCharge = 0;
    }
    
    if (logistics.deliverMethod == 0) {
      //物流配送
      let LogisRrule = logistics.LogisticalRrule;
      if (logistics.freight_type == 0) {
        let freight = LogisRrule.unifiedmoney;
        that.setData({
          freight: freight
        })
      } else if (logistics.freight_type == 1) {
        if (that.data.count > parseInt(LogisRrule.first_num)) {
          let freight = LogisRrule.first_money + (that.data.count - LogisRrule.first_num) / LogisRrule.continued_num * LogisRrule.continued_money;
          that.setData({
            freight: freight
          })
        } else {
          let freight = LogisRrule.first_money;
          that.setData({
            freight: freight
          })
        }
      } else if (logistics.freight_type == 2) {
        if (that.data.weight > parseInt(LogisRrule.first_num)){
          let freight = LogisRrule.first_money + (that.data.weight - LogisRrule.first_num) / LogisRrule.continued_num * LogisRrule.continued_money;
          that.setData({
            freight: freight
          })
        }else{
          let freight = LogisRrule.first_money;
          that.setData({
            freight: freight
          })
        }
      }
    } else if (logistics.deliverMethod == 1) {
      //商家直送
      let distanceIncrease = JSON.parse(logistics.distanceIncrease);
      let nocturnalPriceIncrease = JSON.parse(logistics.nocturnalPriceIncrease);
      let weightIncrease = JSON.parse(logistics.weightIncrease);
      let freight = parseInt(logistics.freight);
      //重量加价
      if (that.data.weight <= 1) {
        freight = freight + parseInt(weightIncrease.weightIncrease_1_val)
      } else if (that.data.weight > 1 && that.data.weight <= 5) {
        freight = freight + parseInt(weightIncrease.weightIncrease_1_val) + (that.data.weight - 1) * parseInt(weightIncrease.weightIncrease_1_5_val)
      } else if (that.data.weight > 5 && that.data.weight <= 10) {
        freight = freight + parseInt(weightIncrease.weightIncrease_1_val) + 4 * parseInt(weightIncrease.weightIncrease_1_5_val) + (that.data.weight - 5) / 5 * parseInt(weightIncrease.weightIncrease_5_10_val)
      } else if (that.data.weight > 10) {
        freight = freight + parseInt(weightIncrease.weightIncrease_1_val) + 4 * parseInt(weightIncrease.weightIncrease_1_5_val) + (that.data.weight - 5) / 5 * parseInt(weightIncrease.weightIncrease_5_10_val)
      }
      //距离加价
      let distance = Math.floor(app.globalData.store.distance / 1000);
      if (distance > 1 && distance <= 3) {
        freight = freight + parseInt(distanceIncrease.distanceIncrease_1_3_val)
      } else if (distance > 3 && distance <= 5) {
        freight = freight + parseInt(distanceIncrease.distanceIncrease_1_3_val) + parseInt(distanceIncrease.distanceIncrease_3_5_val)
      } else if (distance > 5) {
        freight = freight + parseInt(distanceIncrease.distanceIncrease_1_3_val) + parseInt(distanceIncrease.distanceIncrease_3_5_val)
      }
      //夜间加价
      var NowTime = new Date().getHours();
      if (NowTime >= 22 || NowTime < 8) {
        freight = freight + weightIncrease.weightIncrease_1_val + nocturnalPriceIncrease.nocturnalPriceIncrease_22_08_val
      }
      that.setData({
        freight: freight
      })

    } else if (logistics.deliverMethod == 2) {
      //同城快递

    }
    
    let total = getTotal(that, that.data.products, packingCharge, that.data.freight);

    that.setData({
      totalPrice: total,
      orderType: 2,
      Distributions:2,
      packingCharge: packingCharge
    })
  }

  for (var a = 0; a < that.data.products.length; a++) {
    if (res.data.data.pickedUp){
      if (that.data.products[a].isService) {
        let packingCharge = parseInt(res.data.data.pickedUp.packingCharge);
        let total = getTotal(that, that.data.products, packingCharge, 0);
        that.setData({
          packingCharge: packingCharge,
          totalPrice: total,
          orderType: 1,
          Distributions:1,
          isService: false,
          freight: 0
        })
      }
    }else{
      that.setData({
        header: false
      })
    }
    
  }
  console.log("orderType---------------------"+that.data.orderType);
  console.log("Distributions---------------------" + that.data.Distributions);
  
}

var getCount = function (that, products) {
  let count = 0;
  let weight = 0;
  let weights = 0;
  for (let i = 0; i < products.length; i++) {
    count += parseInt(products[i].count);
    weights = parseInt(products[i].weight) * parseInt(products[i].count);
    weight += weights
  }
  that.setData({
    count: count,
    weight: weight / 1000
  })
}
/**
 * 会员优惠
 */
var memberTypeSuccess = function (that, res) {
  if (res.data.data) {
    that.setData({
      member: res.data.data
    })
  }
}

var getOrderIdSuccess = function(that,res){
  if(res.data.data){
    that.setData({
      OrderId:res.data.data.orderId
    })
  }
}
var Feesuccess = function(that,res){
  if(res.data.data){
    let total = getTotal(that, that.data.products, that.data.packingCharge, res.data.data.fee * 100);

    that.setData({
      freight: res.data.data.fee * 100,
      totalPrice: total,
    })
  }
}
